package com.itheima.demo;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 文档搜索
 * @作者 itcast
 * @创建日期 2020/11/7 8:54
 **/
public class EsDemo04 {
    RestHighLevelClient client;


    /**
     * 分页查询
     *
     */
    @Test
    public void page() {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //                         分词查询       要查询的字段      查询条件内容
        builder.query(QueryBuilders.matchQuery("note","同学"));
        int page = 2;
        int pageSize = 3;

        // 分页信息的设置
        builder.from((page - 1) * pageSize);
        builder.size(pageSize);

        // 参数1:哪个字段  参数2: 升序还是降序
        builder.sort("age", SortOrder.DESC);
        builder.sort("gender",SortOrder.ASC);
        printResult(builder);
    }

    /**
     * 排序
     * match
     */
    @Test
    public void sort() {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //                         分词查询       要查询的字段      查询条件内容
        builder.query(QueryBuilders.matchQuery("note","同学"));
        // 参数1:哪个字段  参数2: 升序还是降序
        builder.sort("age", SortOrder.DESC);
        builder.sort("gender",SortOrder.ASC);
        printResult(builder);
    }




    /**
     * note: 分词查询   同学
     * age: 18 ~ 38
     * gender: 0
     */
    @Test
    public void findQuery() {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //note: 分词查询   同学
        boolQueryBuilder.must(QueryBuilders.matchQuery("note","同学"));
        //  * age: 18 ~ 38
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").gte(18).lte(38));
        // * gender: 0
        boolQueryBuilder.filter(QueryBuilders.termQuery("gender",0));
        builder.query(boolQueryBuilder); // 设置bool条件
        printResult(builder);
    }

    /**
     * note:  唱歌javaee
     * match
     */
    @Test
    public void match() {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //                         分词查询       要查询的字段      查询条件内容
        builder.query(QueryBuilders.matchQuery("note","唱歌javaee"));
        printResult(builder);
    }

    /**
     * 18 ~ 28 区间段 上下包含的所有同学
     * range: 范围
     */
    @Test
    public void range() {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.rangeQuery("age").gte(18).lte(28));
        printResult(builder);
    }

    public void printResult(SearchSourceBuilder builder) {
        //        1. 创建搜索请求对象  (SearchRequest )
        SearchRequest searchRequest = new SearchRequest("user");
//        所有的请求参数 通过 SearchSourceBuilder 统一构建
        searchRequest.source(builder);
//        2. 客户端执行 .search搜索方法
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        3. 解析结果 (SearchResponse)
        //searchResponse
//                .getHits 得到查询结果
        SearchHits hits = searchResponse.getHits();
//                .getTotalHits
        System.out.println("查询结果数量==>" + hits.getTotalHits().value);
//                .value 得到查询的结果数量
// 			.getHits
        SearchHit[] docList = hits.getHits();
//                遍历文档列表数组
        for (SearchHit searchHit : docList) {
            String userJson = searchHit.getSourceAsString();
            User user = JSON.parseObject(userJson, User.class);
            System.out.println(user);
        }
// 					.getSource
//                .getHighlight
//                .getAggregations 得到的是聚合总结果
    }
    /**
     * 搜索全部
     */
    @Test
    public void matchAll() throws IOException {
//        1. 创建搜索请求对象  (SearchRequest )
        SearchRequest searchRequest = new SearchRequest("user");
//        所有的请求参数 通过 SearchSourceBuilder 统一构建
        SearchSourceBuilder builder = new SearchSourceBuilder();
// 		.query方法 设置查询条件
        builder.query(QueryBuilders.matchAllQuery());
//        提供工具类创建对应条件类型
//                QueryBuilders
// 		.sort方法 设置排序条件
// 		.from
//                .size   设置分页条件
// 		.highlight 设置高亮条件1
// 		.aggregations 设置聚合条件
//        将builder对象设置到搜索请求的source方法中
        searchRequest.source(builder);
//        2. 客户端执行 .search搜索方法
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//        3. 解析结果 (SearchResponse)
        //searchResponse
//                .getHits 得到查询结果
        SearchHits hits = searchResponse.getHits();
//                .getTotalHits
        System.out.println("查询结果数量==>" + hits.getTotalHits().value);
//                .value 得到查询的结果数量
// 			.getHits
        SearchHit[] docList = hits.getHits();
//                遍历文档列表数组
        for (SearchHit searchHit : docList) {
            String userJson = searchHit.getSourceAsString();
            User user = JSON.parseObject(userJson, User.class);
            System.out.println(user);
        }
// 					.getSource
//                .getHighlight
//                .getAggregations 得到的是聚合总结果
    }



    /**
     * 初始化es的客户端
     */
    @Before
    public void init(){
         client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200))
        );
    }

    /**
     * 关闭客户端
     */
    @After
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
